package org.mii.safeguard_v1.util.interceptor;

import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.mii.safeguard_v1.Constants;
import org.mii.safeguard_v1.base.web.CrudActionSupport;
import org.mii.safeguard_v1.security.dao.AuthorityDao;
import org.mii.safeguard_v1.security.entity.Authority;
import org.mii.safeguard_v1.security.entity.Resource;
import org.mii.safeguard_v1.util.SafeguardSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.GrantedAuthority;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 匿名用户权限控制拦截器。一般来讲，spring security的权限控制足够.<br>
 * 但对于对匿名用户，访问受限资源的时候报404错误，这不是我想看到的！<br>
 * 哥们于是自己写了这个拦截器，直接拦截后跳转到错误页面common/403.jsp
 * 
 * @author QUANXIWEI
 * 
 */
@Deprecated
@SuppressWarnings("serial")
public class AnonymousInterceptor extends AbstractInterceptor {
	@Autowired
	AuthorityDao authorityDao;

	public String intercept(ActionInvocation ai) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		GrantedAuthority[] auths = SafeguardSecurityUtils
				.getCurrentUserAuthorities();
		if (auths == null || auths.length == 0)
			return CrudActionSupport.DENY_ACCESS;

		if (auths.length == 1
				&& auths[0].getAuthority().equalsIgnoreCase(
						Constants.ANONYMOUS_AUTHNAME)) {
			Authority a = authorityDao.findUniqueBy("name", auths[0]
					.getAuthority());
			Set<Resource> rescSet = a.getResources();
			boolean isForbidden = true;
			Pattern p;
			Matcher m;
			for (Iterator<Resource> iterator = rescSet.iterator(); iterator
					.hasNext();) {
				Resource resc = (Resource) iterator.next();
				p = Pattern.compile(resc.getValue());
				m = p.matcher(request.getRequestURI());
				if (m.find()) {
					isForbidden = false;
					break;
				}
			}
			if (isForbidden)
				return CrudActionSupport.DENY_ACCESS;
		}

		return ai.invoke();
	}

}
